<?php
/**
*    Images Saler - Component
*    Author : hm_advert@ymail.com
*    
**/

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.client.helper');
jimport('joomla.application.component.model');
require_once(JPATH_COMPONENT_ADMINISTRATOR . DS . "libs" . DS . "functions.php");

class EcommerceModelProduct extends JModel
{
	
	var $_id = null;
	var $_table = '#__pr_product';
	var $_lists = '';
	var $_data = null;
	var $_params = NULL;
	
	function __construct()
	{
		parent::__construct();

		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
		$this->_params = &JComponentHelper::getParams( 'com_ecommerce' );
	}

	function setId($id)
	{
		$this->_id		= $id;
	}
	
	function getParams(){
		return $this->_params;
	}
	
	function &getData()
	{
		if (empty( $this->_data )) 
		{
			$query = ' SELECT * FROM #__pr_product '.
					'  WHERE id = '.$this->_id;
					
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();	
			if(trim($this->_data->related)!=""){
				$query = ' SELECT id, name FROM #__pr_product '.
						'  WHERE id  in ('.$this->_data->related.')'; 
				$this->_db->setQuery( $query );	
				$this->_data->related = $this->_db->loadObjectList();
			}
			else $this->_data->related=NULL;
		}

		if (!$this->_data) {
			$this->_data = new stdClass();
			$this->_data->id = 0;
			$this->_data->number = null;
			$this->_data->name = null;
			$this->_data->type = null;
			$this->_data->unit = null;
			$this->_data->manufacturer= null;
			$this->_data->parcel = null;
			$this->_data->ingredient = null;
			$this->_data->origin = null;
			$this->_data->country = null;
			$this->_data->price = null;
			$this->_data->image = null;
			$this->_data->basic_info = null;
			$this->_data->instruction = null;
			$this->_data->description = null;
			$this->_data->allergen = null;
			$this->_data->expiry = null;
			$this->_data->quantity = null;
			$this->_data->ordering = null;
			$this->_data->published = null;
			
		}
		return $this->_data;
	}
	
	

	function store()	{
		global $mainframe;
		$row =& $this->getTable();
		if(!$row->bind(JRequest::get('post'))){
			echo '<script>alert("'.$row->getError().'");window.history.go(-1);</script>\n';
			exit();
		}
		//all these lines are used to avoid lost data form post
		$id = JRequest::getVar('id');
		$row->number = JRequest::getVar('number');
		$row->name = JRequest::getVar('name');
		$row->price = doubleval(JRequest::getVar('price'));
		$row->quantity = intval(JRequest::getVar('quantity'));
		$arrCat = JRequest::getVar('cat_id');
		$arrType = JRequest::getVar('type');
		$row->type = implode(",", array_keys($arrType));
		$row->unit= JRequest::getVar('unit');
		$row->parcel= JRequest::getVar('parcel');
		$row->origin= JRequest::getVar('origin');
		$row->expiry= JRequest::getVar('expiry');
		$row->country= JRequest::getVar('country');
		
		$row->description  = JRequest::getVar('description','','post','string',JREQUEST_ALLOWRAW);
		$row->ingredient  = JRequest::getVar('ingredient','','post','string',JREQUEST_ALLOWRAW);
		$row->basic_info  = JRequest::getVar('basic_info','','post','string',JREQUEST_ALLOWRAW);
		$row->instruction  = JRequest::getVar('instruction','','post','string',JREQUEST_ALLOWRAW);
		$row->allergen  = JRequest::getVar('allergen','','post','string',JREQUEST_ALLOWRAW);
		
		
		$row->ordering = intval(JRequest::getVar('ordering'));
		$row->published = intval(JRequest::getVar('published'));
		$row->manufacturer = intval(JRequest::getVar('manufacturer'));
		
		if($_FILES['txtimage']['name']){
			$rand_image = mt_rand();
			$row->image = $rand_image.$_FILES['txtimage']['name'];
		} else {
			$row->image = JRequest::getVar('image');
		}
				
		$row->alias = JFilterOutput::stringURLSafe($row->name);
		//print_r($row);exit;
		if(!$row->store()){
			echo '<script>alert("'.$row->getError().'");window.history.go(-1);</script>\n';
			exit();
		}
		else
		{
			if($id){
				$query = "SELECT category_id FROM #__pr_product_category WHERE product_id = ".$id;
				$this->_db->setQuery($query);
				$oldArrCat = $this->_db->loadResultArray();
				$i = 0;
				foreach($arrCat as $catid){
					if(!in_array($catid, $oldArrCat)){
						$query = "INSERT INTO #__pr_product_category(category_id, product_id) VALUES (".$catid.", ".$id.")";
						$this->_db->setQuery($query); 
						$this->_db->query();
					} else {
						unset($oldArrCat[$i]);
					}
					$i++;
				}
				
				foreach($oldArrCat as $catid){
					$query = "DELETE FROM #__pr_product_category WHERE category_id = ".$catid." AND product_id = ".$id;
					$this->_db->setQuery($query); 
					$this->_db->query();
				}
			} else {
				foreach( $arrCat as $catid ) {
					$query = "INSERT INTO #__pr_product_category (category_id, product_id) VALUES (".$catid.", ".$row->id.")";
					$this->_db->setQuery($query); 
					$this->_db->query();
				}
			}
		
			if($_FILES['txtimage']['name']){
				$prodir = "../components/com_ecommerce/imgupload/";
				$upload = new se_upload();
					
				$pro_image = JRequest::getVar('image','','post','string');
							
				$upload->new_upload('txtimage', 1000000000);
				if(($upload->is_error == 0))
				{	
					if($pro_image!="")
					{
						unlink($prodir.$pro_image);
					} 
					$desphoto = $prodir.$rand_image.$upload->file_name;
					move_uploaded_file($upload->file_tempname, $desphoto);
				}
			}
			
			return true;
		}
	}

	function delete()
	{
		global $mainframe;
		$cid = JRequest::getVar('cid',array(),'','array');
		$db = JFactory::getDBO();
		if(count($cid)> 0 )
		{
			$cids = implode(',',$cid);

			$query = "select * from #__pr_product where id in ($cids)";
			$db->setQuery($query);
			$row = $db->loadObjectList();
						
			foreach ($row as $_file)
			{
				$prodir = "../components/com_ecommerce/imgupload/";
				if(file_exists($prodir . $_file->image))
				{
					unlink($prodir . $_file->image);
				}
			}
			$query = "Delete From #__pr_product Where id in ($cids)";
			$db->setQuery($query);
			if(!$db->query())
			{
				echo "<script> alert('".$db->getErrorMsg()."');window.history.go(-1); </script>\n";
			}
		}

		return true;
	}

	function publish($publish) {
		$cid = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		JArrayHelper::toInteger($cid);
	
		if ( count( $cid ) < 1 ) {
			$action = $publish ? 'Publish' : 'Unpublish';
			JError::raiseError(500, JText::_( 'Select Item to '.$action, true ) );
		}
		
		$cids = implode( ',', $cid );
		$count = count( $cid );
		$query = 'UPDATE #__pr_product'
		. ' SET published = '.(int) $publish
		. ' WHERE id IN ( '.$cids.' )'
		;

		$db =& JFactory::getDBO();
		$db->setQuery( $query );
		if (!$db->query()) {
			JError::raiseError(500, $db->getErrorMsg() );
		}
	
	}
	
	function setPromotion($promotion) {
		$cid = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		JArrayHelper::toInteger($cid);
	
		if ( count( $cid ) < 1 ) {
			$action = $publish ? 'Promotion' : 'UnPromotion';
			JError::raiseError(500, JText::_( 'Select Item to '.$action, true ) );
		}
		
		$cids = implode( ',', $cid );
		$count = count( $cid );
		$query = 'UPDATE #__pr_product'
		. ' SET promotion = '.(int) $promotion
		. ' WHERE id IN ( '.$cids.' )'
		;

		$db =& JFactory::getDBO();
		$db->setQuery( $query );
		if (!$db->query()) {
			JError::raiseError(500, $db->getErrorMsg() );
		}
	
	}

	function orderSection( $uid, $inc)
	{
		$row =& $this->getTable();
		$row->load( $uid );
		$row->move( $inc);
	}

	function saveOrder( &$cid )
	{
		$row =& $this->getTable();
	
		$total		= count( $cid );
		$order		= JRequest::getVar( 'order', array(0), 'post', 'array' );
		JArrayHelper::toInteger($order, array(0));
	
		// update ordering values
		for( $i=0; $i < $total; $i++ )
		{
			$row->load( (int) $cid[$i] );
			if ($row->ordering != $order[$i]) {
				$row->ordering = $order[$i];
				if (!$row->store()) {
					JError::raiseError(500, $db->getErrorMsg() );
				}
			}
		}
	
		$row->reorder();
	}


}

?>